package com.example.project.model.pojo;
import com.example.project.util.StringUtil;
import org.jooq.Record;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: deep
 * \* Date: 17-9-17
 * \* Time: 下午4:11
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class BasePojo {



    public static  <T extends BasePojo> T getInstance(Class<T> tClass,Record record){
        try {

            if (record == null) return null;

            T t=tClass.newInstance();

            //Field[] fields = tClass.getFields();
            List<Field> fields = new ArrayList<>() ;
            Class tempClass = tClass;
            while (tempClass != null) {
                //当父类为null的时候说明到达了最上层的父类(Object类).
                fields.addAll(Arrays.asList(tempClass .getDeclaredFields()));
                tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己
            }

            for (Field field : fields) {

                String captureName= StringUtil.captureName(field.getName());

                String getName="get"+ captureName;

                String setName="set"+ captureName;

                Type type=field.getType();

                try {
                    Method method = getMethos(record.getClass(),getName,type);

                    if (method != null) {
                        Object value = method.invoke(record);
                        if (value != null) {
                            method = getMethos(tClass,setName,type);
                            if (method != null) {
                                method.invoke(t, value);
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return t;
        }catch (Exception e){
            return null;
        }
    }

    private static Method getMethos(Class tcLass,String methodName,Type type){
        Method methodOther=null;
        try{
            Method[] methods=tcLass.getMethods();
            for (Method method:methods) {
                if(methodName.equals(method.getName())){
                    methodOther=method;
                }
            }
        }catch (Exception e){
            getMethos(tcLass.getSuperclass(),methodName,type);
        }
        return methodOther;
    }
}